#!/bin/bash

if [[ $# == 0 || ${1} == "help" ]]; then
	echo "Compiles executables/libraries and maintains installed files. Two tools 'Cmake' and 'stow' are empolyed here. For more information, see https://cmake.org and https://www.gnu.org/software/stow/."
	echo ""
	echo "School of Earth Sciences, Zhejiang University"
	echo "Yi Zhang (yizhang-geo@zju.edu.cn)"
	echo ""
	echo "Usage: ./config.sh [option] [Cmake options]"
	echo ""
	echo "Options:"
	echo "(1) configure: Configure Cmake project(s). This option could take extra Cmake options as in <option>=<value>."
	echo "(2)     build: Build executables/libraries."
	echo "(3)   install: Install executables/libraries to the directory of CMAKE_INSTALL_PREFIX and sym-links them to the target address. This offers a quick and clean remove of the installed files."
	echo "(4)     clean: Clean build/ folder(s)."
	echo "(5) uninstall: Delete the installed files and sym-links."
	echo "(6)      info: Print out current setups."
	echo "(7)      help: Show help information."
	exit 0
fi

package=netcdfcxx_legacy
address=/opt/stow
taress=/usr/local
option="-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=${address}/${package}"

if [[ $# -gt 1 ]]; then
	for opt in "$@"; do
		if [[ ${opt} != "configure" ]]; then
			option="${option} -D${opt}"
		fi
	done
fi

if [[ ${1} == "configure" && ! -d "build/" ]]; then
	mkdir build && cd build && cmake .. ${option}
elif [[ ${1} == "configure" ]]; then
	cd build && rm -rf * && cmake .. ${option}
elif [[ ${1} == "build" ]]; then
	cd build && make
elif [[ ${1} == "install" ]]; then
	cd build && sudo make install
	sudo stow --dir=${address} --target=${taress} -S ${package}
elif [[ ${1} == "clean" ]]; then
	rm -rf build/
elif [[ ${1} == "uninstall" ]]; then
	sudo stow --dir=${address} --target=${taress} -D ${package}
	sudo rm -rf ${address}/${package}
elif [[ ${1} == "info" ]]; then
	echo "package name:" ${package}
	echo "stow address:" ${address}
	echo "target address:" ${taress}
	echo "Cmake options:" ${option}
fi
